require('../../mypublic/css/common.less');
require('../../mypublic/css/index.less');

require('../../public/misc/mediaUpload/css/style.css');
require('../../public/misc/jquery.jqGrid-4.6.0/css/ui.jqgrid.css');
require('../../public/misc/jquery-ui-themes-1.11.2/humanity/jquery-ui.min.css');
require('./index.css');


require("jquery");
var utils = require('@yunke/core/util').default;

require('../../public/misc/jquery.jqGrid-4.6.0/js/i18n/grid.locale-cn');
require('../../public/misc/mediaUpload/js/jquery.form');
require('../../public/misc/mediaUpload/js/myUpload');

require('../../public/js/myservice/side');
require("../../public/js/myservice/authorize");

require('../../public/js/ueditor')

var angular = require('angular');

angular.module('app', [])
    .controller('mainCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.data = {};

        $http.get('/api/index.php?r=/official/article/edit', {
                params: {id: utils.getUrlPara('id')},
                t: new Date().getTime()
            })
            .success(function (res) {
                var data = res;
                $scope.data = data;

                oriFunc(data);
            })
    }])

angular.bootstrap(document, ['app']);

function oriFunc(data) {
    var op = {
        initialFrameHeight: 300
    };
    window.UEDITOR_CONFIG.toolbars = [[
        'fullscreen', 'source', '|', 'undo', 'redo', '|',
        'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
        'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
        'directionalityltr', 'directionalityrtl', 'indent', '|',
        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
        'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
        'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
        'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
        'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
        'print', 'preview', 'searchreplace', 'help', 'drafts'
    ]];
    var editor = new UE.ui.Editor(op);
    editor.render('meEditor');

    // 图片上传
    (function () {
        $(document)
            .ready(function () {
                var $img = $('<img/>').attr({
                    src: data.image_url,
                    width: '210px',
                    height: '140px'
                });
                var $container = $('#preview_container');
                $container.css({
                    'display': 'block'
                }).html('');

                if (data.image_url) {
                    $img.appendTo($container);
                    $('#image_load').css('display', 'none');
                }
            })
            .on('click', '#image_load, .image-upload-container .controllbar .upload', function () {
                $('[role=image-upload-file-input]').val('').trigger("click");
            })
            .on('change', '[role=image-upload-file-input]', function () {
                var uploadForm = $('[role=image-upload-file-form]');
                uploadForm.ajaxSubmit({
                    url: '/api/index.php?r=official/article/media-edit',
                    dataType: "json",
                    success: function (data, status) {
                        if (data.result) {
                            var $img = $('<img/>').attr({
                                src: data.path,
                                width: '210px',
                                height: '140px'
                            });
                            var $container = $('#preview_container');
                            $container.css({
                                'display': 'block'
                            }).html('');
                            $img.appendTo($container);
                            $('#image_load').css('display', 'none');
                            $('#image_url').val(data.path);
                        }
                    }
                })
            })
            .on('mouseover', '.image-upload-container', function (event) {
                $('.image-upload-container .controllbar').show();
            })
            .on('mouseout', '.image-upload-container', function (event) {
                $('.image-upload-container .controllbar').hide();
            })
            .on('click', '.image-upload-container .controllbar .cancel', function (event) {
                var $container = $('#preview_container');
                $container.css({
                    'display': 'none'
                }).html('');
                $('#image_url').val('');
                $('#image_load').css('display', 'block');
            });
    })();

    // 文件上传
    var uploadFileList = [];
    (function () {
        var file_url = data.file_url;
        var file_name = data.file_name;

        var file_urls = file_url.split("@@");
        var file_names = file_name.split("@@");
        for (var i = 1, len = file_urls.length; i < len; i++) {
            uploadFileList.push({
                url: file_urls[i],
                name: file_names[i],
                status: '删除'
            });
        }

        setUploadFile();

        updateUploadFileList();

        function updateUploadFileList() {
            var $container = $('#file_list');
            $container.html('');
            for (var i = 0, len = uploadFileList.length; i < len; i++) {
                $container.append($('<div><div class="fujian_icon"></div>' +
                    '<a class="fujian_text" href="' + uploadFileList[i].url + '"><span style="color: #333333">附件：</span><span>' + uploadFileList[i].name + '</span></a>' +
                    '<a class="fujian_status" href="javascript:;" i="' + i + '"><span class="del" value="' + uploadFileList[i].url
                    + '">' + uploadFileList[i].status + '</span></a></div>'));
            }
        }

        function setUploadFile() {
            var file_urls = "";
            var file_names = "";
            $.each(uploadFileList, function (index, item) {
                if (typeof(item.url) != "undefined") {
                    file_urls += "@@" + item.url;
                    file_names += "@@" + item.name;
                }
            });
            $('#file_url').val(file_urls);
            $('#file_name').val(file_names);
        }

        $(document)
            .on('click', '#file_load', function () {
                $('[role=file-upload-file-input]').val('').trigger("click");
            })
            .on('change', '[role=file-upload-file-input]', function (event) {
                var fileUploadForm = $('[role=file-upload-file-form]');
                var count = 0;
                var src = event.target || window.event.srcElement;
                for (var i = 0, len = src.files.length; i < len; i++) {
                    for (var j = 0; j < uploadFileList.length; j++) {
                        if (src.files[i].name == uploadFileList[j].name) {
                            alert("文件名已存在,请修改本地文件名再重新尝试");
                            return false;
                        }
                    }
                    uploadFileList.push({name: src.files[i].name, status: Math.round(Math.random() * 90) + '%'});
                }
                updateUploadFileList();
                fileUploadForm.ajaxSubmit({
                    url: '/api/index.php?r=official/article/file-upload&a_id=' + $('#a_id').val(),
                    dataType: "json",
                    //data: uploadFileList,
                    success: function (data, status) {
                        $.each(data.path, function (i, item) {
                            uploadFileList[uploadFileList.length - data.path.length + i].url = item;
                            uploadFileList[uploadFileList.length - data.path.length + i].status = '删除';
                        });
                        updateUploadFileList();
                        if (data.result) {
                            setUploadFile()
                        }
                    }
                })
            }).on('click', '.fujian_status', function () {
            uploadFileList.splice($(this).attr('i'), 1);
            updateUploadFileList();
        })
    })();

    var article = {
        /**
         * 判断上传的文件是否都已经完成
         * @returns {boolean}
         */
        isUploadComplete: function () {
            for (var i = 0; i < uploadFileList.length; i++) {
                if (uploadFileList[i].status != "删除") {
                    return false;
                }
            }
            return true;
        },
        ajax: function ($url, $type, $obj) {
            article.type = $type;
            $.ajax({
                url: $url,
                data: sData(),
                type: 'post',
                success: submitSuccess
            });
            function sData() {
                return {
                    'title': $('#title').val(),
                    'imageUrl': $('#image_url').val(),
                    'author': $('#author').val(),
                    'tag': $('#tag').val(),
                    'linkUrl': $('#link_url').val(),
                    'fileUrl': $('#file_url').val(),
                    'fileName': $('#file_name').val(),
                    'content': UE.getEditor('meEditor').getContent(),
                    'dirId': $('#dir_id').val(),
                    'aId': $('#a_id').val(),
                    'desc': $('#desc').val()
                };
            }

            function submitSuccess(data) {
                if (data.retMsg != null && data.retMsg != "") {
                    alert(data.retMsg);
                } else {
                    switch (article.type) {
                        case 1:
                            alert('保存成功！');
                            $('#a_id').val(data.data);
                            window.location.href = "/official/article_list/index.html";
                            break;
                        case 2:
                            alert('保存成功！');
                            window.location.href = "/official/article_edit/index.html";
                            break;
                        case 3:
                            alert('保存成功！');
                            window.location.href = "/official/article_list/index.html";
                            break;
                        case 4:
                            alert('保存并复制成功！');
                            window.location.href = "/official/article_edit/index.html?id=" + data.data;
                            break;
                        default:
                            break;
                    }
                }
            }
        },
        type: 0,
        bind: function () {
            $('#save').bind('click', function () {
                if (!article.isUploadComplete()) {
                    alert("您还有文件正在上传中，请稍等");
                    return false;
                }
                article.ajax('/api/index.php?r=/official/article/save', 1);
            });
            $('#save_create').bind('click', function () {
                if (!article.isUploadComplete()) {
                    alert("您还有文件正在上传中，请稍等");
                    return false;
                }
                article.ajax('/api/index.php?r=/official/article/save', 2);
            });
            $('#save_close').bind('click', function () {
                if (!article.isUploadComplete()) {
                    alert("您还有文件正在上传中，请稍等");
                    return false;
                }
                article.ajax('/api/index.php?r=/official/article/save', 3);
            });
            $('#save_copy').bind('click', function () {
                if (!article.isUploadComplete()) {
                    alert("您还有文件正在上传中，请稍等");
                    return false;
                }
                article.ajax('/api/index.php?r=/official/article/save&copy=1', 4);
            });
            $('#no_save').bind('click', function () {
                window.location.href = "/official/article_list/index.html";
            });
        }
    }
    article.bind();

    $('#meEditor').html(data.content);

    $('.del').click(function () {
        $.ajax({
            url: '/api/index.php?r=/official/article/fujian-del&a_id=' + data.a_id + '&url=' + $(this).attr('value'),
            type: "GET",
            success: function (data) {
                history.go(0);
            }
        })
    })
}